﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Threading;
using System.Reflection;

namespace ESRP
{
    public partial class ConturiRezumatFrm : FrmRezumat
    {
        const String txtToateConturile = "Toate conturile!";
        const String txtConturiUtilizate = "Conturile utilizate!";

        private Int16 AnCurent = 2000;
        private String _adauga = String.Empty;
        /// <summary>
        /// contul care va fi adaugat la lansarea rezumatului
        /// </summary>
        public String AdaugaCont
        {
            get { return _adauga; }
            set { _adauga = value; }
        }
        public String FiltruDenumire = String.Empty;
        /// <summary>
        /// daca se lucreaza cu soldurile initiale defalcate pe capitole(jurnale)
        /// </summary>
        private Boolean SolduriInitialePeJurnale = false;
        /// <summary>
        /// daca se folosesc soldurile precedente
        /// </summary>
        private Boolean SolduriPrecedenteVizibile = false;
        private String _contParinteSelectat = "N/A";
        public String ContParinteSelectat
        {
            get { return _contParinteSelectat; }
            set { _contParinteSelectat = value; }
        }

        public Int32 idxBAfiseaza = -1;
        public Int32 idxBAnterior = -1;
        public Int32 idxBUrmator = -1;
        public Int32 idxBSolduriInitiale = -1;
        /// <summary>
        /// categoria contului 0 - in bilant, 2 in afara bilantului
        /// </summary>
        private Int16 categorie = 0;
        private String typeCont = "A";
		private Int16 NivelContAfisat = 0;
        /// <summary>
        /// stiva cu conturile parinte
        /// </summary>
        private Stack<String> ContParinte = new Stack<string>();
        /// <summary>
        /// stiva cu randurile anterioare care trebuie selectate
        /// </summary>
        private Stack<DataGridViewRow> m_RanduriAnteriore = new Stack<DataGridViewRow>();
        /// <summary>
        /// nivelVirtual e true daca ne aflam pe un nivel fara nici o inregistrare
        /// - de pe un asfel de nivel nu se poate merge mai in adancime
        /// </summary>
        private Boolean nivelVirtual = false;
        public String PrefixCont = String.Empty;

        public ConturiRezumatFrm(ModuleClass mInfo,Int16 cat=0,String prefix="")
            : base(mInfo)
        {
            PrefixCont = prefix;
            categorie = cat;
            ContParinte.Push("N/A");
            InitializeComponent();
            HandleAfterAdd += new AfterAddHandler(ConturiRezumatFrm_HandleAfterAdd);
            HandleBeforeAdd += new EventHandler(ConturiRezumatFrm_HandleBeforeAdd);
            HandleBeforeSearch += new EventHandler(ConturiRezumatFrm_HandleBeforeAdd);
            this.HandleBeforeDelAfterMessage += DocumenteFrm_HandleBeforeDelAfterMessage;


            #region Arhiva
            //this.conturiTableAdapter.SetTableName(ModuleInfo.AnArhiva);
            if (ModuleInfo.AnArhiva != String.Empty)
                this.ReadOnly = true; 
            #endregion

            eSRPDataSet.Conturi.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;    
            eSRPDataSet.Conturi.TerminalColumn.DefaultValue = true;
            eSRPDataSet.Conturi.EsteAnaliticColumn.DefaultValue = true;
            eSRPDataSet.Conturi.DebitInitialColumn.DefaultValue = 0;
            eSRPDataSet.Conturi.CreditInitialColumn.DefaultValue = 0;
            eSRPDataSet.Conturi.DebitPrecedentColumn.DefaultValue = 0;
            eSRPDataSet.Conturi.CreditPrecedentColumn.DefaultValue = 0;
            eSRPDataSet.Conturi.RulajCreditColumn.DefaultValue = 0;
            eSRPDataSet.Conturi.RulajDebitColumn.DefaultValue = 0;
            eSRPDataSet.Conturi.SoldColumn.DefaultValue = 0;
            ActiveControl = conturiDGV;
            EnableMainBrowseButton = false;
        }

        void ConturiRezumatFrm_HandleBeforeAdd(object sender, EventArgs e)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            AfiseazaToateConturile(con, true,true);
            InchideConexiune(con);
        }

        void ConturiRezumatFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            DataGridViewRow dc = conturiDGV.CurrentRow;
            if (dc == null)
                return;
            {
                Boolean isTerminal = true;
                if (dc.Cells["TerminalColumn"].Value != DBNull.Value)
                    isTerminal = Convert.ToBoolean(dc.Cells["TerminalColumn"].Value);
                if (isTerminal == false)
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.LightBlue;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                }
                else
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.White;
                    ///se modifica tipul contului
                    ///
					/// daca se lucreaza cu jurnale defalcate nu se pot modifica
					if (SolduriInitialePeJurnale)
					{
						conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
						conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
						conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
						conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
					}
					else
					{
						String tip = conturiDGV[TipContColumn.Index, dc.Index].Value.ToString();
						if (tip == "A")
						{
							conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
							conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
							conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
						}
						if (tip == "P")
						{
							conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
							conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
							conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
						}
						if (tip == "B")
						{
							conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
							conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;

						}
					}
                }

            }
        }

        private void ConturiRezumatFrm_Load(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            //adauga tabela principala
            AddSource(conturiBindingSource, conturiTableAdapter.Adapter);
            conturiTableAdapter.AddStatementCompleteHandler(Command_StatementCompleted);
            conturiCorespTableAdapter.AddStatementCompleteHandler(Command_StatementCompleted);
            conturiSpecialeTableAdapter.AddStatementCompleteHandler(Command_StatementCompleted);
            SqlConnection con = DeschideConexiune(workConnString);
            this.conturiTableAdapter.Connection = con;
            this.conturiCorespTableAdapter.Connection = con;
            this.conturiCorespTableAdapter.Fill(this.eSRPDataSet.ConturiCoresp, ModuleInfo.CodUnitate);
            this.conturiSpecialeTableAdapter.Connection = con;
            this.conturiSpecialeTableAdapter.Fill(this.eSRPDataSet.ConturiSpeciale, ModuleInfo.CodUnitate);


            #region Adaugare cont N/A
            ///verifica existenta contului radacina pentru unitatea curenta
            ///
            SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM [Conturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='N/A'",
                    conturiTableAdapter.Connection);
            Object ret = cmd.ExecuteScalar();
            if (ret != null && Convert.ToInt32(ret) == 0)
            {
                cmd.CommandText = "INSERT INTO [Conturi]([Cont],[CodUnitate],[Denumire],[Tip],[Terminal],[ContParinte],[EsteAnalitic],[Categorie]) VALUES ('N/A'," + ModuleInfo.CodUnitate.ToString() + ",'Principal','B',0,'N/A',1,0)";
                cmd.ExecuteNonQuery();
            } 
            #endregion
            #region Initializeaza planul de conturi pentru o unitate noua
            ///insereaza un nou plan de conturi
            ///
            cmd.CommandText = "SELECT Count(*) FROM [Conturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'N/A'";
            ret = cmd.ExecuteScalar();
            if (ret != null && Convert.ToInt32(ret) == 0)
            {

                ret = GetSetupValue("BalconSetup", "TipUnitate", ModuleInfo.CodUnitate, conturiTableAdapter.Connection);
                String val = String.Empty;
                if (ret == null || ret == DBNull.Value)
                {
                    while (ret == null)
                    {
                        MessageBox.Show("Modulul Balante Contabile nu a fost configurat. \nVa rugam sa-l configurati!",
                                "Eroare",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Hand);
                        ///configurare modul
                        #region Configurare Modul BalCon
                        FrmMainMdi frm = MdiParent as FrmMainMdi;
                        Assembly asm = frm.GetModule("erpforms");
                        if (asm == null)
                            return;
                        String numeClasa = "ERPForms.BalconSetupFrm";
                        Type mModule = asm.GetType(numeClasa);

                        if (mModule != null)
                        {
                            FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                               new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                            newFrm.ShowDialog();
                        }
                        #endregion
                        ///configurare modul-----------------------------------
                        ret = GetSetupValue("BalconSetup", "TipUnitate", ModuleInfo.CodUnitate, conturiTableAdapter.Connection);
                    }
                }
                val = ret.ToString();
                PopuleazaConturi(val, conturiTableAdapter.Connection);
            }
            #endregion
            #region Actualizare solduri
            /*cmd.CommandText = "balcon_UpdateSoldCont";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("codUnitate", ModuleInfo.CodUnitate));
            cmd.ExecuteNonQuery();*/
            #endregion            

            this.tipContTableAdapter.Connection = this.conturiTableAdapter.Connection;
            tipContTableAdapter.AddStatementCompleteHandler(Command_StatementCompleted);
            #region Seteaza conturile care vor fi afisate, cele utilizate sau toate
            this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
            String DeAfisat = String.Empty;
            //if (_adauga != String.Empty) <- asa a fost pana in 26.11.2009
            if (ContParinteSelectat!="N/A")
            {
                ContParinte.Push(ContParinteSelectat);
                eSRPDataSet.Conturi.ContColumn.DefaultValue = _adauga;
                ///daca e un cont selectat, ordoneaza analiticele
                conturiBindingSource.Sort = "[SortValue]";
            }


            NivelContAfisat = Convert.ToInt16(GetSetupValue("BalconSetup", "NivelAfisareConturi", ModuleInfo.CodUnitate, con));
            String afis = GetSetariLocale(this.conturiTableAdapter.Connection, "CUSE", "1",ModuleInfo.CodUnitate);
            if (afis == "1")
            {
				if (NivelContAfisat == 0)
					this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
				else{
                    if (ContParinte.Peek()!="N/A")
                        this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
                    else
					    this.conturiTableAdapter.FillByLungimeFolosit(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, (byte)categorie, 3 + NivelContAfisat * 2, FiltruDenumire);
                }
                DeAfisat = txtToateConturile;
            }
            else
            {
				if (NivelContAfisat == 0)
					this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire,PrefixCont);
				else
                {
                    if (ContParinte.Peek()!="N/A")
                        this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                    else
                        this.conturiTableAdapter.FillByLungime(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, 3 + NivelContAfisat * 2, (byte)categorie, FiltruDenumire);
                }
					
                DeAfisat = txtConturiUtilizate;
            } 
            #endregion 


           

            AddSource(conturiCorespBindingSource, conturiCorespTableAdapter.Adapter);
            AddSource(conturiCorespBindingSource1, conturiCorespTableAdapter.Adapter);
            AddSource(conturiSpecialeBindingSource, conturiSpecialeTableAdapter.Adapter);

            
            if (ModuleInfo.AnArhiva == String.Empty)
            {
                AddButton("Salvare[F9]", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                if (SelectionAddOn)
                    HandleSalvare += new EventHandler(Selectie);
                else
                    HandleSalvare += new EventHandler(Salvare);
            }


            AddButton("Proprietati", global::ERPStudio.Properties.Resources.furl_48, ProprietatiConturi, ToolStripItemAlignment.Right, false);
            idxBAfiseaza = AddButton(DeAfisat, global::ERPStudio.Properties.Resources.rss_48, AfiseazaConturiUtilizate, ToolStripItemAlignment.Right, false);
            idxBSolduriInitiale = AddButton("Solduri initiale", global::ERPStudio.Properties.Resources.wallet, SolduriInitialePeCapitole, ToolStripItemAlignment.Right, false);
            AddButton("Schimba Cont", global::ERPStudio.Properties.Resources.book_next, SchimbaCont, ToolStripItemAlignment.Right, false);

            idxBAnterior = AddButton("Sintetic", global::ERPStudio.Properties.Resources.arrow_left_green_48, RevenireNivelAnterior, ToolStripItemAlignment.Left, false);
            idxBUrmator = AddButton("Analitice", global::ERPStudio.Properties.Resources.arrow_right_green_48, tSBNext_Click, ToolStripItemAlignment.Left, false);

            List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
            AddDropDownItem("Bilant", bilantToolStripMenuItem_Click, ref items);
            AddDropDownItem("In afara bilantului", inAfaraBilantuluiToolStripMenuItem_Click, ref items);
            AddDropDown("Categorie", global::ERPStudio.Properties.Resources.delicious_48, (EventHandler)null, items.ToArray(), ToolStripItemAlignment.Left);

 
            eSRPDataSet.Conturi.CategorieColumn.DefaultValue = categorie;


            #region Setare tip cont pentru adaugare
            if (ContParinteSelectat != "N/A")
            {
                cmd.CommandText = "SELECT [Tip] FROM [Conturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" + ContParinteSelectat + "'";
                cmd.CommandType = CommandType.Text;
                ret = cmd.ExecuteScalar();
                if (ret != null)
                {
                    typeCont = ret.ToString();
                }
            }
            eSRPDataSet.Conturi.TipColumn.DefaultValue = typeCont; 
            #endregion
            InchideConexiune(this.conturiTableAdapter.Connection);
            if (ContParinte.Peek() != "N/A")
                eSRPDataSet.Conturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            eSRPDataSet.Conturi.ContParinteColumn.DefaultValue = ContParinte.Peek();
            
            ///varinata in care porneste direct in adaugare
            if (_adauga != String.Empty)
            {
                Adauga(this, null);
                
            }
            this.SetStatusNavigationButtons();
            Setup();
            ActiveControl = conturiDGV.EditingControl;
            Cursor.Current = Cursors.Default;
        }

        private void PopuleazaConturi(String TipUnitate,SqlConnection con)
        {
            SqlCommand cmd = new SqlCommand("balcon_PopuleazaConturiUnitateNoua", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ex.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, cmd);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
            }
        }

        private void AfiseazaToateConturile(SqlConnection con,Boolean afis,Boolean verifica)
        {
            this.conturiTableAdapter.Connection = con;
            if (verifica)
            {
                if (afis)
                {
                    if (listTSButton[idxBAfiseaza].Text == txtToateConturile)
                    {
                        if (NivelContAfisat == 0)
                            this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                        else
                            this.conturiTableAdapter.FillByLungime(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, 3 + NivelContAfisat * 2, (byte)categorie, FiltruDenumire);
                    }

                }
                else
                {
                    if (listTSButton[idxBAfiseaza].Text == txtConturiUtilizate)
                    {
                        if(NivelContAfisat==0)
                            this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
                        else
                            this.conturiTableAdapter.FillByLungimeFolosit(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, (byte)categorie, 3 + NivelContAfisat * 2, FiltruDenumire);
                    }
                }
            }
            else
            {
                if (afis)
                {
                    if(NivelContAfisat==0)
                        this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                    else
                        this.conturiTableAdapter.FillByLungime(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, 3 + NivelContAfisat * 2, (byte)categorie, FiltruDenumire);
                }
                else
                {
                    if(NivelContAfisat==0)
                        this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
                    else
                        this.conturiTableAdapter.FillByLungimeFolosit(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, (byte)categorie, 3 + NivelContAfisat * 2, FiltruDenumire);

                }

            }

        }

        private void AfiseazaConturiUtilizate(object sender, EventArgs e)
        {
            Salvare(this, null);
            if (EroareSalvare)
                return;
 
            try
            {
                SqlConnection con = DeschideConexiune(workConnString);
               this.tipContTableAdapter.Connection = con;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                if (idxBAfiseaza != -1)
                {
                    if (e == null)
                    {
                        ///nu schimba afisarile
                        if (listTSButton[idxBAfiseaza].Text != txtToateConturile)
                            AfiseazaToateConturile(con, true, false);
                        else
                            AfiseazaToateConturile(con, false, false);
                    }
                    else
                    {
                        SetSetariLocale(con, "CUSE", listTSButton[idxBAfiseaza].Text == txtToateConturile ? "0" : "1", ModuleInfo.CodUnitate);
                        ///schimba afisarile
                        if (listTSButton[idxBAfiseaza].Text == txtToateConturile)
                        {
                            AfiseazaToateConturile(con, true, true);
                            listTSButton[idxBAfiseaza].Text = txtConturiUtilizate;
                        }
                        else
                        {
                            AfiseazaToateConturile(con, false, true);
                            listTSButton[idxBAfiseaza].Text = txtToateConturile;
                        }

                    }
                }
                else
                { 
                    //tribunal
                    AfiseazaToateConturile(con, true, false);
                }
                InchideConexiune(this.conturiTableAdapter.Connection);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

        private void conturiDGV_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (e.ListChangedType != ListChangedType.Reset || conturiDGV.Rows.Count <= 0)
                return;
            MyTrace(e.ListChangedType + "," + conturiDGV.Rows.Count.ToString());
            foreach (DataGridViewRow dc in conturiDGV.Rows)
            {
                Boolean isTerminal = true;
                if (dc.Cells["TerminalColumn"].Value!= DBNull.Value)
                    isTerminal = Convert.ToBoolean(dc.Cells["TerminalColumn"].Value);
                if (isTerminal == false)
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.LightBlue;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                }
                else
                {
                
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.White;

                    /// daca se lucreaza cu jurnale defalcate nu se pot modifica
					if (SolduriInitialePeJurnale)
					{
						conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
						conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
						conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
						conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
					}
					else
					{
						// se modifica in functie de tipul contului
						String tip = conturiDGV[TipContColumn.Index, dc.Index].Value.ToString();
						if (tip == "A")
						{
							conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
							conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
							conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
						}
						if (tip == "P")
						{
							conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
							conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
							conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
						}
						if (tip == "B")
						{
							conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
							conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
							conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;

						}
					}
                }
            }
        }

        private void Setup()
        {

            SqlConnection wConn = DeschideConexiune(workConnString);
            

            Object ret = GetSetupValue("BalconSetup", "SoldPrecedentActiv", ModuleInfo.CodUnitate, wConn);
            Boolean val = false;
            if (ret == null || ret == DBNull.Value)
            {
                while (ret == null)
                {
                    /*MessageBox.Show("Modulul Balante Contabile nu a fost configurat. \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    ///configurare modul
                    #region Configurare Modul BalCon
                    FrmMainMdi frm = MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("erpforms");
                    if (asm == null)
                        return;
                    String numeClasa = "ERPForms.BalconSetupFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                           new object[] { _moduleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                        newFrm.ShowDialog();
                    }
                    #endregion
                    ///configurare modul-----------------------------------
                     */
                    SqlCommand comcfg = new SqlCommand("INSERT INTO BalconSetup (CodUnitate,AnCurent,LunaCurenta) VALUES (" + ModuleInfo.CodUnitate.ToString() + "," + DateTime.Now.Year.ToString() + "," + DateTime.Now.AddMonths(-1).Month.ToString() + ")",
                         wConn);
                    comcfg.ExecuteNonQuery();
                    ret = GetSetupValue("BalconSetup", "SoldPrecedentActiv", ModuleInfo.CodUnitate, wConn);
                }

            }

			
            SolduriPrecedenteVizibile = (Boolean)ret;
            DebitPrecedentColumn.Visible = SolduriPrecedenteVizibile;
            CreditPrecedentColumn.Visible = SolduriPrecedenteVizibile;
			if (!SolduriPrecedenteVizibile)
			{
				///daca nu sunt afisate soldurile precedente facem fereastra mai mica
				///
				this.Width -= 130;
			}


            #region Setare latime coloane conturi in functie de cel mai lung cont

            SqlCommand com = new SqlCommand("select MAX(LEN(ltrim(RTRIM(Cont)))) from Conturi where CodUnitate=" + ModuleInfo.CodUnitate.ToString(),wConn);
            Object rId = com.ExecuteScalar();
            if (rId != null && rId != DBNull.Value)
            {
                ContColumn.Width = Convert.ToInt32(rId) * 8;
            }

            #endregion

            #region setare mod de lucru solduri initiale pe jurnale
            ret = GetSetupValue("BalconSetup", "SolduriInitialeDefalcateJurnale", ModuleInfo.CodUnitate, wConn);
            SolduriInitialePeJurnale = Convert.ToBoolean(ret);
            if (!SolduriInitialePeJurnale)
                listTSButton[idxBSolduriInitiale].Visible = false;
            com = new SqlCommand("select Count(*) from [JurnaleSolduriInitiale] where CodUnitate=" + ModuleInfo.CodUnitate.ToString(), wConn);
            rId = com.ExecuteScalar();
            if (rId != null && rId != DBNull.Value)
            {
                while (Convert.ToInt32(rId) == 0 && SolduriInitialePeJurnale)
                {
                    CopiazaSolduriInitialePeJurnaleFrm frm = new CopiazaSolduriInitialePeJurnaleFrm(ModuleInfo);
                    frm.ShowDialog();
                    rId = com.ExecuteScalar();
                }
            } 
            #endregion

			ret = GetSetupValue("BalconSetup", "NivelAfisareConturi", ModuleInfo.CodUnitate, wConn);
			NivelContAfisat = Convert.ToInt16(ret);


            
            InchideConexiune(wConn);
        }
        private Boolean GetSum(ref Decimal sumaDeb,ref Decimal sumaCre)
        { 
            sumaDeb = Decimal.Zero;
            sumaCre = Decimal.Zero;
             return true ;
        }

        private void conturiDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            ///headerul gridului
            if (e.RowIndex == -1)
                return;
            //neinitializat gridul
            if ((conturiDGV.Columns["DebitInitialColumn"] == null) || (conturiDGV.Columns["CreditInitialColumn"] == null))
                return;
            
            if (e.ColumnIndex == conturiDGV.Columns["DebitInitialColumn"].Index ||
                (e.ColumnIndex == conturiDGV.Columns["CreditInitialColumn"].Index))
            {
                //CalculateSum();
            }
            if (e.ColumnIndex == TipContColumn.Index && e.RowIndex>=0)
            { 
                ///se modifica tipul contului
                ///
                String tip = conturiDGV[e.ColumnIndex, e.RowIndex].Value.ToString();
                if (tip == "A")
                {
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].ReadOnly = true;
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].Style.BackColor = Color.LightGray;

                }
                if (tip == "P")
                {
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].Style.BackColor = Color.LightGray;
                }
                if (tip == "B")
                {
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                }
                conturiDGV[DebitInitialColumn.Index, e.RowIndex].Value = 0;
                conturiDGV[CreditInitialColumn.Index, e.RowIndex].Value = 0;

            }

        }

        override public void Salvare(object sender, EventArgs args)
        {
            String contCur = String.Empty;
            if (conturiBindingSource.Current != null)
            {
                ESRPDataSet.ConturiRow cr = ((DataRowView)conturiBindingSource.Current).Row as ESRPDataSet.ConturiRow;
                if (cr != null)
                    contCur = cr.Cont;
            }
            base.Salvare(this, args);

            if (EroareSalvare && args!=null)
            {   
                try
                {
                    this.conturiTableAdapter.Connection = DeschideConexiune(workConnString);
                    ///nu schimba afisarile
                    ///
                    if (listTSButton[idxBAfiseaza].Text != "Afiseaza toate conturile!")
                        this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                    else
                        this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, "N/A", ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);                        
                    
                    InchideConexiune(this.conturiTableAdapter.Connection);
                }
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
            }

            #region Lansare thread actualizare
            if (NoRecUpdated > 0)
            {
                //Thread newThread = new Thread(ConturiRezumatFrm.UpdateSoldCont);
                //newThread.Start(new InfoThr(workConnString,ModuleInfo.CodUnitate));
            }

            #endregion
            if (contCur != String.Empty)
            {
                int poz = conturiBindingSource.Find("Cont", contCur);
                if (poz != -1)
                    conturiBindingSource.Position = poz;
            }
        }

        public struct InfoThr
        {
            public String ConnStr;
            public Int16 CodUnitate;
            public InfoThr(String cStr, Int16 _CodUnitate)
            {
                ConnStr = cStr;
                CodUnitate = _CodUnitate;
            }
        }


        private static void UpdateSoldCont(object info)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(((InfoThr)info).ConnStr));
            cmd.CommandText = "balcon_UpdateSoldCont";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("codUnitate", ((InfoThr)info).CodUnitate));
            cmd.ExecuteNonQuery();
            InchideConexiune(cmd.Connection);
        }


        /// <summary>
        /// avanseaza un nivel in planuri de conturi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void conturiDGV_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //daca ne aflam pe un nivel virtual nu mai avansam
            if (nivelVirtual || e.RowIndex<0)
                return;

            
            typeCont = conturiDGV.Rows[e.RowIndex].Cells["TipContColumn"].Value.ToString();
            if (typeCont != String.Empty)
                conturiDGV.Columns["TipContColumn"].ReadOnly = true;
            ContParinte.Push(conturiDGV.Rows[e.RowIndex].Cells["ContColumn"].Value.ToString());
            m_RanduriAnteriore.Push(conturiDGV.Rows[e.RowIndex]);
            
            Salvare(this, null);
            if (EroareSalvare)
                return;
            this.conturiTableAdapter.Connection = DeschideConexiune(workConnString);

            if (listTSButton[idxBAfiseaza].Text != "Afiseaza toate conturile!")
            {
                //// toate la gramada
                this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
            }
            else
            {
                // cele pe care se lucreaza
                this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
            }

            InchideConexiune(this.conturiTableAdapter.Connection);

            conturiBindingSource.Sort = "[SortValue]";
            nivelVirtual = conturiBindingSource.Count == 0;
            SetStatusNavigationButtons();

            #region Setari valori implicite
            eSRPDataSet.Conturi.CategorieColumn.DefaultValue = categorie;
            if (typeCont != String.Empty)
                eSRPDataSet.Conturi.TipColumn.DefaultValue = typeCont;
            if (ContParinte.Peek() != "N/A")
                eSRPDataSet.Conturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            eSRPDataSet.Conturi.ContParinteColumn.DefaultValue = ContParinte.Peek();
            #endregion
        }
        /// <summary>
        /// revine la nivelul anterior de conturi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RevenireNivelAnterior(object sender, EventArgs e)
        {
            //scoate contul din varful stivei pentu selectie
            /// daca stiva e goala nu face nimic
            if (ContParinte.Count == 0)
                return;
            
            Salvare(this, null);
            if (EroareSalvare)
                return;
            String contAnt = ContParinte.Pop();
            try
            {
                this.conturiTableAdapter.Connection = DeschideConexiune(workConnString);
                this.tipContTableAdapter.Connection = this.conturiTableAdapter.Connection;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                if (listTSButton[idxBAfiseaza].Text != txtToateConturile)
                {
                    //// toate la gramada
                    if (ContParinte.Peek() != "N/A")
                        this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                    else
                    {
                        if (NivelContAfisat == 0)
                            this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                        else
                            this.conturiTableAdapter.FillByLungime(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, 3 + NivelContAfisat * 2, (byte)categorie, FiltruDenumire);

                    }
                }
                else
                {
                    // cele pe care se lucreaza
                    if (ContParinte.Peek() != "N/A")
                        this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
                    else
                    {
                        if (NivelContAfisat == 0)
                            this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
                        else
                            this.conturiTableAdapter.FillByLungimeFolosit(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, (byte)categorie, 3 + NivelContAfisat * 2, FiltruDenumire);

                    }
                }

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                InchideConexiune(this.conturiTableAdapter.Connection);
            }

            nivelVirtual = conturiBindingSource.Count == 0;
            SetStatusNavigationButtons();

            /// selecteaza nodul bunic
            ///
            DataGridViewRow dr = m_RanduriAnteriore.Pop();
            int rdSel = conturiBindingSource.Find("Cont", contAnt);
            conturiBindingSource.Position = rdSel;
            
            if (ContParinte.Peek() == "N/A")
            {
                typeCont = String.Empty;
                conturiDGV.Columns["TipContColumn"].ReadOnly = false;
                conturiBindingSource.Sort = "[SortValue]";
            }

            #region Setari valori implicite
            eSRPDataSet.Conturi.CategorieColumn.DefaultValue = categorie;
            if (typeCont != String.Empty)
                eSRPDataSet.Conturi.TipColumn.DefaultValue = typeCont;
            if (ContParinte.Peek() != "N/A")
                eSRPDataSet.Conturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            eSRPDataSet.Conturi.ContParinteColumn.DefaultValue = ContParinte.Peek(); 
            #endregion
            
            
        }

        private void SetStatusNavigationButtons()
        {
            if (idxBAnterior == -1 || idxBUrmator == -1)
                return;
            if (ContParinte.Peek() == "N/A")
            {
                listTSButton[idxBAnterior].Enabled = false;
                listTSButton[idxBUrmator].Enabled = true;
                this.Text = "Rezumat Conturi";
            }
            else
            {
                if (!nivelVirtual)
                {
                    listTSButton[idxBAnterior].Enabled = true;
                    listTSButton[idxBUrmator].Enabled = true;
                }
                else
                {
                    listTSButton[idxBAnterior].Enabled = true;
                    listTSButton[idxBUrmator].Enabled = false;                
                }
                this.Text = "Rezumat Conturi - " + ContParinte.Peek();
            }                
        }

        private void tSBNext_Click(object sender, EventArgs e)
        {
            if(conturiDGV.SelectedCells.Count == 0){
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }
            conturiDGV_CellDoubleClick(conturiDGV,
                new DataGridViewCellEventArgs(1, conturiDGV.SelectedCells[0].RowIndex));
        }

        private void bilantToolStripMenuItem_Click(object sender, EventArgs e)
        {
            categorie = 0;
            AfiseazaConturiUtilizate(this, null);
        }

        private void inAfaraBilantuluiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            categorie = 2;
            AfiseazaConturiUtilizate(this, null);
        }

        private void ProprietatiConturi(object sender, EventArgs e)
        {
            if (conturiDGV.SelectedCells.Count == 0)
            {
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }
            int SavePos = conturiBindingSource.Position;
            ConturiSpecialeFrm frm = new ConturiSpecialeFrm(conturiDGV.Rows[conturiDGV.SelectedCells[0].RowIndex].Cells["ContColumn"].Value.ToString(),
                conturiDGV[ContParinteColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value.ToString(),
                Convert.ToByte(conturiDGV[CategorieColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value),
                Convert.ToBoolean(conturiDGV[TerminalColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value),
                Convert.ToBoolean(conturiDGV[esteAnaliticColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value),
                ModuleInfo);
            frm.ShowDialog();
            if (frm.MustRefresh)
            {
                AfiseazaConturiUtilizate(this, null);
                conturiBindingSource.Position = SavePos;
            }
        }

        override public void SetCurentUnit(short vCodUnitate)
        {
            ModuleInfo.CodUnitate = vCodUnitate;
            AfiseazaConturiUtilizate(this, null);
        }

        private void conturiDGV_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            /// valideaza soldurile initiale pentru conturile bifunctionale
            /// 
            String tip = conturiDGV[TipContColumn.Index, e.RowIndex].Value.ToString();
            if (tip == "B")
            {
                Decimal sid = Convert.ToDecimal(conturiDGV[DebitInitialColumn.Index, e.RowIndex].Value);
                Decimal sic = Convert.ToDecimal(conturiDGV[CreditInitialColumn.Index, e.RowIndex].Value);
                if (sid != Decimal.Zero && sic != Decimal.Zero)
                {
                    MessageBox.Show("Soldul initial al contului " + conturiDGV[ContColumn.Index, e.RowIndex].Value.ToString()
                        + " poate fi pe debit sau pe credit. \nVa rugam sa corectati eroarea!\nPentru anularea modificarilor apasati tasta ESCAPE!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    //e.Cancel = true;
                    //conturiDGV[CreditInitialColumn.Index, e.RowIndex].Selected = true;
                }
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            //Setup(conn);
        }
        /// <summary>
        /// cand se apasa enter, controlul activ este luna, anul
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {

        }

        private void NoteContabile(object sender, EventArgs e)
        { 
             if(conturiDGV.SelectedCells.Count == 0){
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }
             conturiDGV_CellContentClick(sender, new DataGridViewCellEventArgs(SoldColumn.Index, conturiDGV.SelectedCells[0].RowIndex));
        }

        private void conturiDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == SoldColumn.Index)
            {
                NoteContabileRezumatFrm _frmNCR = new NoteContabileRezumatFrm(null,ModuleInfo);
                _frmNCR.MdiParent = this.MdiParent;
                _frmNCR.SelectionAddOn = true;
                _frmNCR.filtruNote = conturiDGV.SelectedRows[0].Cells["ContColumn"].Value.ToString();
                _frmNCR.Show();

                
            }
        }

        
        bool DocumenteFrm_HandleBeforeDelAfterMessage(object sender, EventArgs args, Boolean dingrid)
        {
            foreach (DataRowView dl in conturiCorespBindingSource)
                conturiCorespBindingSource.Remove(dl);
            foreach (DataRowView dl in conturiCorespBindingSource1)
                conturiCorespBindingSource1.Remove(dl);
            foreach (DataRowView dl in conturiSpecialeBindingSource)
                conturiSpecialeBindingSource.Remove(dl);
            return true;
        }

        private void SchimbaCont(object sender, EventArgs e)
        {
            if (conturiDGV.SelectedRows != null)
            { 
                DataGridViewRow dr = conturiDGV.SelectedRows[0];
                ESRPDataSet.ConturiRow cr = ((DataRowView)dr.DataBoundItem).Row as ESRPDataSet.ConturiRow;
                String txt = "Se modifica denumirea contului: " + cr.Cont +". Va rugam introduceti noua denumire:";
                GetValueFrm frmGet = new GetValueFrm(txt, cr.Cont);
                frmGet.ShowDialog();
                MessageBoxFrm mbt = new MessageBoxFrm("Confirmare", "Va rugam sa confirmati modificarea contului "+cr.Cont + " in contul " + frmGet.RetValue + ".", "Se aplica modificarea?", MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
                if(mbt.ShowDialog()== System.Windows.Forms.DialogResult.No)
                    return;
                SqlCommand cmd = new SqlCommand("balcon_ChangeCont",DeschideConexiune(workConnString));
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("oldCont", cr.Cont));
                cmd.Parameters.Add(new SqlParameter("newCont", frmGet.RetValue));
                cmd.Parameters.Add(new SqlParameter("codUnitate", ModuleInfo.CodUnitate));
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    InchideConexiune(cmd.Connection);
                    MessageBoxFrm mbt2 = new MessageBoxFrm("Eroare", ex.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                    mbt2.AddButton("Ieşire", 70, mbt2.MessageBoxFrm_Click_Yes);
                    mbt2.ShowDialog();
                    return;
                }
                finally {
                    InchideConexiune(cmd.Connection);
                }

                AfiseazaConturiUtilizate(this, null);
            }
        }


        private void SolduriInitialePeCapitole(object sender, EventArgs e)
        {
            if (conturiBindingSource.Current == null)
                return;
            ESRPDataSet.ConturiRow cRow = ((DataRowView)conturiBindingSource.Current).Row as ESRPDataSet.ConturiRow;
            if (cRow == null)
                return;
            if (!cRow.Terminal)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Soldul initial se poate introduce doar pentru conturile care nu au analitice sau alte conturi subordonate!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }
            SolduriInitialeJurnaleFrm frm = new SolduriInitialeJurnaleFrm(ModuleInfo, cRow, SolduriPrecedenteVizibile);
            frm.ShowDialog();

            try
            {
                this.conturiTableAdapter.Connection = DeschideConexiune(workConnString);
                if (listTSButton[idxBAfiseaza].Text != "Afiseaza toate conturile!")
                {
                    //// toate la gramada
                    if (NivelContAfisat == 0)
                        this.conturiTableAdapter.FillByCategorieContParinte(this.eSRPDataSet.Conturi, ((byte)categorie), ContParinte.Peek(), ModuleInfo.CodUnitate, FiltruDenumire, PrefixCont);
                    else
                        this.conturiTableAdapter.FillByLungime(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, 3 + NivelContAfisat * 2, (byte)categorie, FiltruDenumire);
                }
                else
                {
                    // cele pe care se lucreaza
                    if (NivelContAfisat == 0)
                        this.conturiTableAdapter.FillUsedCategorie(this.eSRPDataSet.Conturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,PrefixCont);
                    else
                        this.conturiTableAdapter.FillByLungimeFolosit(this.eSRPDataSet.Conturi, ModuleInfo.CodUnitate, (byte)categorie, 3 + NivelContAfisat * 2, FiltruDenumire);
                }

            }
            catch (System.Exception ex)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ex.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }
            finally
            {
                InchideConexiune(this.conturiTableAdapter.Connection);
            }
        }


    }

    //public class ConturiTableAdapterEx : ESRP.ESRPDataSetTableAdapters.ConturiTableAdapter
    //{
    //    public ConturiTableAdapterEx():base()
    //    { 
        
    //    }
    //    public void SetTableName(String an)
    //    {
    //        foreach (SqlCommand cmd in this.CommandCollection)
    //        {
    //            if (cmd.CommandText.Contains("dbo.Conturi"))
    //                cmd.CommandText = cmd.CommandText.Replace("FROM dbo.Conturi", "FROM [arhConturi]");
    //            else
    //                cmd.CommandText = cmd.CommandText.Replace("FROM Conturi", "FROM [arhConturi]");
    //        }
    //    }
    //}

}
